<template>
    <div class="dataAcquisition">
        <el-row :gutter="20" type="flex">
            <el-col :span="15">
            <NewCard title="材料列表" :border="false">
                <div class="table-box">
                    <el-table
                        :data="tableList"
                        style="width: 100%"
                        highlight-current-row
                        @row-click="rowClick">
                        <el-table-column label="选择" type="selection" width="50">
                        </el-table-column>
                        <el-table-column label="序号" type="index" width="80">
                        </el-table-column>
                        <el-table-column label="材料名称" width="200">
                            <template slot-scope="scope">
                                <p>{{ scope.row.name ? scope.row.name : "--" }}</p>
                            </template>
                        </el-table-column>
                        <el-table-column label="材料要求">
                            <template slot-scope="scope">
                                <p>{{ scope.row.requirement }}</p>
                            </template>
                        </el-table-column>
                        <el-table-column label="样本" width="80">
                            <template slot-scope="scope">
                                <!-- materialSampleList -->
                                <p>{{scope.row.materialSampleList.length == 0 ? "未上传": "已上传"}}</p>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="bottomBtn">
                    <el-button @click="addMaterialBtn" v-if="bottomBtnShow">+添加材料</el-button>
                    <el-input 
                        v-model="bottomBtnValue" 
                        v-else 
                        @blur="bottomBtnShow=true" 
                        @keyup.enter.native="addMaterials"
                        ref="bottBtn">
                    </el-input>
                </div>
            </NewCard>
            </el-col>
            <el-col :span="9">
            <NewCard title="编辑">
                <div class="editForm">
                    <el-form
                        ref="form"
                        :model="editFrom"
                        label-width="100px"
                        label-position="left">
                        <el-form-item label="材料名称">
                            <el-input v-model="editFrom.name" placeholder="请输入..."></el-input>
                        </el-form-item>
                        <el-form-item label="材料要求">
                            <el-input
                                v-model="editFrom.requirement"
                                type="textarea"
                                rows="8"
                                resize="none"
                                placeholder="请输入...">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="材料样本">
                        <div class="uploadImg-list">
                            <div
                            class="img-box"
                            v-for="(img, index) in pictureObj"
                            :key="index">
                                <img :src="img" class="avatar" />
                                <i class="el-icon-error" @click="removeImg(img)"></i>
                            </div>
                        </div>
                        <el-upload
                            :auto-upload="false"
                            class="avatar-uploader"
                            action="#"
                            :show-file-list="false"
                            :on-change="uploadMaterial">
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        </el-form-item>
                    </el-form>
                    </div>
                <SubBtn>
                <template slot="btn">
                    <el-button round @click="removeForm">删除</el-button>
                    <el-button type="primary" round @click="saveForm">保存</el-button>
                </template>
                </SubBtn>
            </NewCard>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import NewCard from "@/wss/components/newCard.vue";
import SubBtn from "@/wss/components/subBtn.vue";

import {UrltoFile} from "@/wss/utils/wss.js";
import {
  getProjectMaterialListApi,
  editProjectMaterialApi,
  addProjectMaterialApi,
  removeProjectMaterialApi,
  removeMaterialSampleApi,
} from "@/wss/newApi_3-24/work/projectMaterial.js";
export default {
    components:{NewCard,SubBtn},
    props:{
      cascaderValue:{
        type: Array,
      },
    },
    data(){
        return{
            // 分页参数
            pageing: { pageNum: 1, pageSize: 10, total: 0 },

            // 流程步骤的材料收集表格数据
            tableList: [],
            typeId:'',//当前选择的项目类型二级id
            
            bottomBtnShow:true,//流程步骤的材料收集底部按钮
            bottomBtnValue:'',//流程步骤的材料收集底部输入值

            // 流程步骤的材料收集表单数据
            editFrom: {
                name: "",
                requirement: "",
                status: "0",
                typeId: "",
                materialSampleList: [],
            },
            //流程步骤的材料收集 上传的图片
            pictureObj:'',

            // 已上传文件转成文件流形式的数据
            fileRaw: [],
            //上传的图片
            pictureObj: [],
            // 上传图片列表
            fileList: [],
        }
    },
    mounted(){
      this.getProjectMaterialList()//获取所选的项目类型下的项目材料
    },
    methods:{
        
        //获取所选的项目类型下的项目材料
        async getProjectMaterialList() {
            //获取所选的项目类型最后一个类型的id
            let typeId = this.cascaderValue[this.cascaderValue.length - 2];
            let result = await getProjectMaterialListApi({typeId});
            if (result.code == 200) {
                this.tableList = result.rows;
            }
        },

        // ****************流程步骤的材料收集********************************************************
      
        // 点击添加材料
        addMaterialBtn(){
            //显示输入框
            this.bottomBtnShow = false
            //输入框自动获取焦点
            this.$nextTick(()=>{
                this.$refs.bottBtn.focus()
            })
        },

        //输入框按回车的回调
        async addMaterials(){
            if(this.bottomBtnValue){
                await this.addProjectMaterial(); //添加项目材料
                this.getProjectMaterialList(); //更新项目材料列表
                //隐藏输入框
                this.bottomBtnShow = true;
                this.bottomBtnValue = "";
            }else{
                this.$message({type:'warning',message:'请输入材料名称'})
            }
        },

        //上传图片的回调
        uploadMaterial(file, fileList) {
            //上传判断
            const isJPGPNG =
                file.raw.type === "image/jpeg" || file.raw.type === "image/png";
            const isLt2M = file.raw.size / 1024 / 1024 < 2;

            if (!isJPGPNG) {
                this.$message.error("上传样本只能是 JPG/PNG 格式!");
                return;
            } else {
                if (!isLt2M) {
                this.$message.error("上传样本大小不能超过 2MB!");
                return;
                } else {
                // if (fileList && fileList.length > 1) {
                //   fileList.shift();
                // }
                this.fileList.push(file);
                this.pictureObj.push(URL.createObjectURL(file.raw));
                }
            }
        },

        //点击表格某一行 把某一行的数据赋值给编辑表单
        rowClick(row) {
            //清空之前编辑的数据
            this.editFrom = {
                name: "",
                requirement: "",
                status: "0",
                typeId: "",
                materialSampleList: [],
            };
            this.pictureObj = [];
            this.fileRaw = [];
            this.fileList = [];
            //获取typeID
            this.editFrom.typeId = this.cascaderValue[this.cascaderValue.length - 1];
            // 合并对象
            let newObj = Object.assign(this.editFrom, row);
            this.editFrom = newObj;
            //获取材料样本的地址回显
            this.editFrom.materialSampleList.forEach((item) => {
                this.pictureObj.push(item.file);
            });

            //把已上传的图片转成文件流的形式 fileRaw *****************
            this.editFrom.materialSampleList.forEach((item) => {
                //获取文件名称
                let fileName = item.file.substring(item.file.lastIndexOf("/") + 1);
                //转成文件流
                UrltoFile(item.file,(file) => {
                    this.fileRaw.push(file);
                },
                fileName
                );
            });
            //把已上传的图片转成文件流的形式 fileRaw ***************** end
        },

        //点击保存按钮
        async saveForm() {
            if (!this.editFrom.id) {
                this.$message({
                message: "请选择项目材料",
                type: "warning",
                });
            } else {
                await this.editProjectMaterial(); //编辑接口
                this.getProjectMaterialList(); //重新获取项目材料
            }
        },

        // ****************流程步骤的材料收集********************************************************end

        // 接口 *************************

        //添加项目材料
        async addProjectMaterial() {
            //获取所选的项目类型最后一个类型的id
            let typeId = this.cascaderValue[this.cascaderValue.length - 2];
            let name = this.bottomBtnValue;
            // 创建一个form表单
            let formDate = new FormData();
            formDate.set("name", name);
            formDate.set("typeId", typeId);
            let result = await addProjectMaterialApi(formDate);
            // console.log(result);
            if (result.code == 200) {
                this.$message({
                message: "添加成功！",
                type: "success",
                });
            } else {
                this.$message.error("添加失败!");
            }
        },

        // 编辑项目材料的接口
        async editProjectMaterial() {
            // 创建一个form表单
            let editFrom = this.editFrom;
            let formDate = new FormData();
            //项目材料
            formDate.set("name", editFrom.name);
            formDate.set("typeId", editFrom.typeId);
            formDate.set("requirement", editFrom.requirement);
            formDate.set("status", editFrom.status);
            formDate.set("createBy", editFrom.createBy);
            formDate.set("createTime", editFrom.createTime);
            formDate.set("id", editFrom.id);
            this.fileRaw.forEach((item, i) => {
                formDate.append(`file`, item);
            });
            this.fileList.forEach((item, i) => {
                formDate.append(`file`, item.raw);
            });

            //打印formDate
            // for (var key of formDate.entries()) {
            //     console.log(key[0] + ', ' + key[1]);
            // }

            //发请求
            let result = await editProjectMaterialApi(formDate);
            if (result.code == 200) {
                this.$message({
                message: "编辑成功！",
                type: "success",
                });
            } else {
                this.$message.error("编辑失败!");
            }
        },

        //删除按钮的回调
        async removeForm() {
            if (!this.editFrom.id) {
                this.$message({
                message: "请选择项目材料",
                type: "warning",
                });
            } else {
                await this.removeProjectMaterial(); //删除按钮的接口
                this.getProjectMaterialList(); //重新获取项目材料
            }
        },

        //删除按钮的接口
        async removeProjectMaterial() {
            let id = this.editFrom.id;
            let result = await removeProjectMaterialApi(id);
            if (result.code == 200) {
                this.$message({
                message: "删除成功！",
                type: "success",
                });
            } else {
                this.$message.error("删除失败!");
            }
        },

        // 删除材料样本的回调
        async removeImg(img) {
            let id = "";
            // 根据img路径去拿到当前点击删除的项目材料样本id
            this.editFrom.materialSampleList.forEach((item) => {
                if (item.file == img) {
                id = item.id;
                }
            });
            await this.removeMaterialSample(id); // 删除材料样本的接口
            await this.getProjectMaterialList(); //重新获取项目材料

            //更新显示的材料样本
            this.pictureObj.splice(this.pictureObj.indexOf(img), 1);
        },

        // 删除材料样本的接口
        async removeMaterialSample(id) {
            let result = await removeMaterialSampleApi(id);
            if (result.code == 200) {
                this.$message({
                message: "删除成功！",
                type: "success",
                });
            } else {
                this.$message.error("删除失败!");
            }
        },

    },
}
</script>

<style scoped>
/* 流程步骤的材料收集******************** */
/* 表格数据 */
.dataAcquisition{
  height: 95%;
  padding: 0 20px;
}
.dataAcquisition .el-row{
  height: 100%;
}
.dataAcquisition .el-card{
    position: relative;
}
.dataAcquisition >>> .el-card__body>div{
    height: 88%;
    overflow-y: auto;
}

/* 表格样式 */
.el-table {
  margin-bottom: 50px;
}
::v-deep .el-table .el-table__header-wrapper th {
  background-color: #fff;
}
::v-deep .el-table th.is-leaf {
  border-top: 1px solid #efefef;
  border-bottom: 1px solid #efefef;
}
::v-deep .el-table th > .cell {
  font-size: 12px;
  color: #909aaa;
}
::v-deep .el-table__body tr.current-row > td {
  background-color: #ebecf0;
}
::v-deep .el-table .cell,
::v-deep .el-table .cell p {
  margin: 0;
  font-size: 14px;
  color: #2e3f5e;
}
::v-deep .el-table .cell .el-button {
  color: #f87a23;
}
::v-deep .el-table .cell .el-table__expand-icon i::before {
  content: "\E791";
}
::v-deep .el-table td {
  /* border-bottom: 0; */
}
::v-deep .el-table td .islight {
  color: #f87a23;
}
::v-deep .el-table .el-table__expanded-cell[class*="cell"] {
  padding: 0;
}
::v-deep .el-table__expanded-cell .el-table::before {
  height: 0;
}
::v-deep .el-table__expanded-cell .el-table th.is-leaf {
  border-top: 0;
}
::v-deep .el-table__expanded-cell .el-table td {
  border-bottom: 0;
  padding: 6px 0;
}

::v-deep .el-table__footer-wrapper tbody td {
  background-color: #fff;
  font-weight: bold;
  color: #2e3f5e;
}

/* 添加材料 */
.bottomBtn {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 9;
}
.bottomBtn .el-button {
  width: 100%;
  border: 0;
  border-top: 1px solid #ecedf0;
  background-color: #f8f8f8;
  line-height: 25px;
  color: #606e84;
}
.bottomBtn .el-input {
  width: 100%;
}
::v-deep .bottomBtn .el-input .el-input__inner {
  height: 46px;
  line-height: 46px;
  border: 0;
  border-top: 1px solid #ecedf0;
  background-color: #f8f8f8;
  text-align: center;
}

/* 编辑 */
.editForm {
  margin-bottom: 80px;
  margin-top: 20px;
}
.editForm >>> .el-textarea__inner {
  font-family: Microsoft Yahei;
}

/* 上传 */
.expertRev .el-button {
  position: absolute;
  top: 10px;
  right: 20px;
  padding: 8px 10px;
  font-size: 13px;
}
::v-deep .dataAcquisition .avatar-uploader .el-upload {
  border: 0;
  position: relative;
  overflow: hidden;
  width: 100%;
  text-align: left;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.uploadImg-list .img-box {
  position: relative;
  margin-bottom: 15px;
}
.uploadImg-list img {
  display: block;
  width: 100%;
}
.uploadImg-list .img-box > i {
  position: absolute;
  right: 10px;
  top: 10px;
  z-index: 9;
  opacity: 0;
  transition: all 0.3s;
  cursor: pointer;
}
.uploadImg-list .img-box:hover > i {
  opacity: 1;
}
.uploadImg-list .img-box > i:hover {
  color: #f87a23;
}

::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  line-height: 130px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

/* 右侧按钮样式 */
::v-deep .subBtn {
  padding: 8px 30px;
}
::v-deep .subBtn .el-button {
  width: 100px;
  padding: 8px 0;
  font-size: 14px;
  color: #606e84;
}
::v-deep .subBtn .el-button--primary {
  background-color: #f87a23;
  border-color: #f87a23;
  color: #fff;
}
::v-deep .subBtn .el-button--primary:hover {
  background-color: #f87a23;
  border-color: #f87a23;
  color: #fff;
}
</style>